package com.kaikai.edu.service.impl;

import com.kaikai.commonutils.JwtUtils;
import com.kaikai.commonutils.MD5;
import com.kaikai.commonutils.R;
import com.kaikai.edu.entity.EduUser;
import com.kaikai.edu.entity.ao.EduLoginAO;
import com.kaikai.edu.entity.vo.EduUserRoleVo;
import com.kaikai.edu.mapper.EduUserMapper;
import com.kaikai.edu.service.EduUserService;
import com.kaikai.edu.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class EduUserServiceImpl implements EduUserService {

    private static Logger logger = LoggerFactory.getLogger(EduUserServiceImpl.class);

    @Autowired
    private  RedisUtil redisUtil;

    @Autowired
    private EduUserMapper userMapper;

    @Override
    public R loginAuth(EduLoginAO userAo) {
        try {
            //密码加密
            String password = MD5.encrypt(userAo.getPassword());
            userAo.setPassword(password);
            EduUserRoleVo eduUser = userMapper.loginAuth(userAo);
            if (eduUser == null) {
                return R.error().message("用户账号或密码错误");
            }
            Map<String, Object> data = new HashMap<>();
            Map<String, Object> user = new HashMap<>();
            user.put("status", eduUser.getStatus());
            user.put("accountName", eduUser.getAccountName());
            user.put("nickName", eduUser.getNickName());
            user.put("salt", eduUser.getSalt());
            user.put("userId", eduUser.getUserId());
            user.put("nickName", eduUser.getNickName());
            user.put("permissions", eduUser.getPermissions());
            user.put("roles", eduUser.getRoles());
            String token = JwtUtils.getJwtToken(eduUser.getUserId(), eduUser.getAccountName());
            data.put("token", token);
            data.put("user", user);
            //更新登录信息
            EduUser updateUser = new EduUser();
            updateUser.setUserId(eduUser.getUserId());
            updateUser.setLastLoginTime(new Date());
            userMapper.updateUser(updateUser);
            //添加缓存
            redisUtil.set("token"+eduUser.getUserId(),token,1, TimeUnit.DAYS);
            return R.ok().data(data);
        }catch (Exception e){
            logger.error("登录异常，原因"+e);
            return R.error().message("登录异常");
        }
    }

    @Override
    public EduUser getUserByAccountName(String accountName) {
        return userMapper.getUserByAccountName(accountName);
    }


}
